package com.timesheet.gui.efforttracker.uiforms.section;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;

public class SectionToolbar extends Composite {

	private final FormToolkit toolkit = new FormToolkit(Display.getCurrent());

	private ToolBarManager toolBarManager = new ToolBarManager(SWT.FLAT);

	private Section sctnNewSection;

	/**
	 * Create the composite.
	 * 
	 * @param parent
	 * @param style
	 */
	public SectionToolbar(Composite parent, int style) {
		super(parent, style);
		/*addDisposeListener(new DisposeListener() {

			public void widgetDisposed(DisposeEvent e) {
				toolkit.dispose();
			}
		});*/
		toolkit.adapt(this);
		toolkit.paintBordersFor(this);
		setLayout(new GridLayout(1, false));

		sctnNewSection = toolkit.createSection(this, style);
		sctnNewSection.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		toolkit.paintBordersFor(sctnNewSection);

		ToolBar bar = new ToolBar(sctnNewSection, SWT.FLAT | SWT.HORIZONTAL);
		ToolItem item = new ToolItem(bar, SWT.PUSH);
		item.setText("Ur Item Name");

		sctnNewSection.setTextClient(bar);

		createToolbar(sctnNewSection);

	}

	public void setText(String text) {
		sctnNewSection.setText(text);
	}

	public Section getSection() {
		return sctnNewSection;
	}

	/**
	 * Liefert das Attribut toolBarManager
	 * 
	 * @return Wert von toolBarManager
	 */
	public ToolBarManager getToolBarManager() {
		return toolBarManager;
	}

	protected void createToolbar(Section section) {

		toolBarManager.add(new Action("print") {

			@Override
			public void run() {
				System.out.println("PRINT");
			}
		});

		toolBarManager.add(new Action("Refresh") {

			@Override
			public void run() {
				System.out.println("Refresh");
			}
		});

		createSectionToolbar(section, toolBarManager);
	}

	/**
	 * create a toolbar in the passed section
	 * 
	 * @param section
	 * @param toolBarManager
	 */
	protected void createSectionToolbar(Section section, ToolBarManager toolBarManager) {
		Composite toolbarComposite = toolkit.createComposite(section);
		toolbarComposite.setBackground(null);
		toolBarManager.createControl(toolbarComposite);
		section.clientVerticalSpacing = 0;
		section.descriptionVerticalSpacing = 0;
		section.setTextClient(toolbarComposite);
	}
}